/**
 * Created by Jie on 2017/2/4.
 */
var async = require('async');
var db = require('../../util/pool');
var format = require('../../util/json2sql');
var _ = require('underscore');
var data = require('../../util/result');

var Menu = function() {};

//通过id获取数据
Menu.prototype.one = function (_id,callback) {
    var sql = format.one('menu',_id);
    db.queryFirst(sql,function (err,results) {
        if(!err){
            callback(null,results);
        }
    })
}
//添加数据
Menu.prototype.insert = function(json, callback) {
    var sql = format.insert('menu',json);
    db.exec(sql,function (err,results) {
        if(!err){
            callback(null,results);
        }
    });
};
//编辑数据
Menu.prototype.edit = function (json,callback) {
    var sql = format.update('menu',json);
    db.exec(sql,function (err,results) {
        if(!err){
            callback(null,results);
        }
    })
}
//删除数据
Menu.prototype.del = function (id,callback) {
    var sql = format.delete('menu',id);
    db.exec(sql,function (err,results) {
        if(!err){
            callback(null,results);
        }
    })
}
//数据列表
Menu.prototype.list = function(where, callback) {
    var countSql = format.count('menu',where);
    var dataSql = '';
    var idsSql = format.ids('menu',where);
    var result = {};
    async.waterfall([
        function(callback) {
            db.queryFirst(countSql,function (err,results) {
                if(!err){
                    result.total = results.rows;
                    callback(null,results);
                }
            });
        },
        function(onearg, callback) {
            db.query(idsSql,function (err,results) {
                if(!err){
                    callback(null,results);
                }
            });
        },
        function(twoarg, callback) {
            var ids = [];
            for(var i=0;i<twoarg.length;i++){
                ids.push(twoarg[i].id);
            }
            dataSql = format.select('menu',where,ids.join(','));
            db.query(dataSql,function (err,results) {
                if(!err){
                    result.error = 0;
                    result.data = results;
                    callback(null,result);
                }
            });
        }
    ], function(error, result) {
        callback(null, result);
    });
};
//读取所有数据
Menu.prototype.all = function(_cond, callback) {
    var sql = format.all('menu',_cond.where,_cond.order);
    db.query(sql,function (err,results) {
        if(!err){
            callback(null,data.result(0,'ok',results));
        }else{
            callback(null,data.result(1,'异常'));
        }
    })
};

module.exports = Menu;